from concurrent import futures
import logging

import grpc

from db import factory
from entity import migrate_pb2
from grpc_service import migrate_pb2_grpc
import json

class MigrateService(migrate_pb2_grpc.MigrateServiceServicer):
    def send(self, request, context):
        params: dict = json.loads(request.data)
        db_type = request.db
        key = params.get("key")
        dest_url = params.get("dest_url")
        data_list = params.get("data_list")

        # 获取对应数据库的实现类
        server_impl_clz = factory.get_migrate_server_factory(db_type)
        server_impl = server_impl_clz(key, db_type, dest_url)
        server_impl.execute_insert(data_list)
        return migrate_pb2.Reply(message='ok')

    def start(self, request, context):
        params:dict = json.loads(request.data)
        db_type = request.db
        key = params.get("key")
        dest_url = params.get("dest_url")
        schema = params.get("schema")
        table_name = params.get("table_name")


        # 获取对应数据库的实现类
        server_impl_clz = factory.get_migrate_server_factory(db_type)
        server_impl = server_impl_clz(key,db_type,dest_url)
        server_impl.create_table(table_name,schema)

        return migrate_pb2.Reply(message='ok')


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    migrate_pb2_grpc.add_MigrateServiceServicer_to_server(MigrateService(), server)
    server.add_insecure_port('[::]:8088')
    server.start()
    server.wait_for_termination()


if __name__ == '__main__':
    logging.basicConfig()
    serve()
